<?php

/**
 * This is the model class for table "users".
 *
 * The followings are the available columns in table 'users':
 * @property integer $id
 * @property string $first_name
 * @property string $last_name
 * @property string $secondary_name
 * @property string $email
 * @property string $salt
 * @property string $password
 * @property string $created
 * @property string $last_visit
 * @property integer $role
 */
class Users extends CActiveRecord {
	const ROLE_OWNER = 55; //програміст
	const ROLE_ADMIN = 6; // адмін
	const ROLE_MODER = 5; // модератор
	const ROLE_USER = 1; // звичайний юзер
	const ROLE_BANNED = 0; // забанений користувач

        public $rememberMe;
        public $retry_password;
        private $_identity;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Users the static model class
	 */
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'users';
	}

	public static function get_array_role() {
		return array(
			self::ROLE_USER => Yii::t('main', 'Звичайний користувач'),
			self::ROLE_MODER => Yii::t('main', 'Модератор'),
			self::ROLE_ADMIN => Yii::t('main', 'Адмін'),
		);
	}

	public static function get_role_text($status=0) {
		$array = self::get_array_role();

		if (!empty($array[$status])){
			return $array[$status];
		}else{
			return FALSE;
		}
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('first_name, last_name, secondary_name, email, salt, password, created, role', 'required','on' => 'create'),
			array('email', 'email', 'checkMX'=>TRUE, 'on' => 'create'),
			array('email', 'check_email', 'on' => 'create','on' => 'create'),
			array('role', 'numerical', 'integerOnly' => true,'on' => 'create'),
			array('first_name, last_name, secondary_name, email, password', 'length', 'max' => 255,'on' => 'create'),
			array('salt', 'length', 'max' => 32,'on' => 'create'),
			array('password', 'required','on' => 'update_password_adminom'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
//			array('id, first_name, last_name, secondary_name, email, salt, password, created, last_visit, role', 'safe', 'on' => 'search'),
                        //login
			array('email, password', 'required','on' => 'login'),
			array('email', 'email','on' => 'login'),
			array('rememberMe', 'boolean','on' => 'login'),
			array('password', 'authenticate','on' => 'login'),
			//register users
			array('first_name, last_name, email, password,retry_password,phone', 'required','on' => 'register_users'),
			array('email', 'unique' ,'on' => 'register_users'),
			array('email', 'email','checkMX'=>TRUE, 'on' => 'register_users'),
			array('email', 'check_email' ,'on' => 'register_users'),
			array('role', 'numerical', 'integerOnly' => true,'on' => 'register_users'),
			array('password','compare' , 'compareAttribute'=>'retry_password', 'on' => 'register_users'),
			array('first_name, last_name, secondary_name, email, password,retry_password, phone', 'length', 'max' => 255,'on' => 'register_users'),
                    
		);
	}

                /**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->email,$this->password);

			if(!$this->_identity->authenticate()){
				$this->addError('password','Не вырний логын або пароль');
			}
		}
	}
        
        
        /**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->email,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			//$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
                        $duration= 3600*24*30 ; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}
        
	public function check_email($attribute, $params) {
		$criteria = new CDbCriteria();
		$criteria->condition = 'email = :email';
		$criteria->params = array(':email' => $this->email);

		$result = Users::model()->find($criteria);

		if (!empty($result)){
			$this->addError('email', 'Цей email вже зайнятий іншим користувачем');
		}
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id' => 'ID',
			'first_name' => 'Імя',
			'last_name' => 'Фамілія',
			'secondary_name' => 'По батькові',
			'email' => 'Email',
			'salt' => 'Salt',
			'password' => 'Пароль',
			'created' => 'Дата регістрації',
			'last_visit' => 'Останій візит',
			'role' => 'Роль',
			'rememberMe' => 'Запамятати мене',
			'retry_password' => 'Повторити пароль',
			'phone' => 'phone'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('id', $this->id);
		$criteria->compare('first_name', $this->first_name, true);
		$criteria->compare('last_name', $this->last_name, true);
		$criteria->compare('secondary_name', $this->secondary_name, true);
		$criteria->compare('email', $this->email, true);
		$criteria->compare('salt', $this->salt, true);
		$criteria->compare('password', $this->password, true);
		$criteria->compare('created', $this->created, true);
		$criteria->compare('last_visit', $this->last_visit, true);
		$criteria->compare('role', $this->role);

		$criteria->condition='role<>55';

		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
		));
	}

	public function get_salt() {
		$arr = array('a', 'b', 'c', 'd', 'e', 'f',
			'g', 'h', 'i', 'j', 'k', 'l',
			'm', 'n', 'o', 'p', 'r', 's',
			't', 'u', 'v', 'x', 'y', 'z',
			'A', 'B', 'C', 'D', 'E', 'F',
			'G', 'H', 'I', 'J', 'K', 'L',
			'M', 'N', 'O', 'P', 'R', 'S',
			'T', 'U', 'V', 'X', 'Y', 'Z',
			'1', '2', '3', '4', '5', '6',
			'7', '8', '9', '0', '.', ',',
			'(', ')', '[', ']', '!', '?',
			'&', '^', '%', '@', '*', '$',
			'<', '>', '/', '|', '+', '-',
			'{', '}', '`', '~');
		// Генерируем пароль
		$pass = "";

		for ($i = 0; $i < 20; $i++) {
			// Вычисляем случайный индекс массива
			$index = rand(0, count($arr) - 1);
			$pass .= $arr[$index];
		}

		return md5($pass);
	}

	public function get_password_with_salt($pass,$salt){
		return md5($pass.$salt);
	}

	
	

}